package com.infobip.ftpclient;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;

public class FTPClient {

	/**
	 * Main class for starting parallel FTP upload
	 * 
	 * @param args
	 */
	public static void main(String[] args) {

		// Parse String[] args to HashMap
		HashMap<String, String> properties = FTPClientUtil.parseCommands(args);

		// Array of FTPStatistic that will be used for storing statistic
		ArrayList<FTPStatistic> ftpStatistics = new ArrayList<FTPStatistic>();

		String filesStr = properties.get("files");

		// Get separated array of files
		File[] files = FTPClientUtil.parseFiles(filesStr);

		// List of threads for parallel ftp upload
		ArrayList<FTPClientThread> threadsArray = new ArrayList<FTPClientThread>();

		if (files != null) {
			// Check number of files, maximum is 5.
			if (!(files.length > 5)) {

				// Run all upload threads
				for (int i = 0; i < files.length; i++) {

					FTPStatistic ftpStatistic = new FTPStatistic();

					FTPClientThread ftpClientThread = new FTPClientThread(
							properties.get("host"), properties.get("user"),
							properties.get("pass"), files[i], ftpStatistic);

					ftpStatistics.add(ftpStatistic);
					threadsArray.add(ftpClientThread);
					ftpClientThread.start();
				}

				System.out.println("Uploading files, please wait ...");

				// Waiting threads execution and printing statistics
				boolean isAnyAlive = true;
				while (isAnyAlive) {
					for (int k = 0; k < threadsArray.size(); k++) {
						if (!threadsArray.get(k).isAlive()) {
							FTPClientUtil
									.printStatistics(threadsArray.get(k).statistic);
							threadsArray.remove(k);
						}
					}
					if (threadsArray.size() == 0) {
						isAnyAlive = false;
					}
				}
				FTPClientUtil.printTotalStatistics(ftpStatistics);
			} else {
				System.out.println("Invalid number of files. Maximum is 5.");
			}
		} else {
			System.out.println("Invalid number of files. Minimum is 1.");
		}
	}

}
